package com.example.testsbjenkins.zip;

/**
 * @author: lt
 * @date: 2022/7/20 14:52
 * @Description: todo
 */
import cn.hutool.core.date.StopWatch;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.zip.GZIPOutputStream;

/**
 * @author zhangzhixiang
 * @version V1.0
 * @Title: PackFilesUtil.java
 * @Description: 文件压缩工具类
 * @date 2020-01-07 19:40:50
 */
public class PackFilesUtil {

    private static final Logger LOG = LoggerFactory.getLogger(PackFilesUtil.class);

    /**
     * tar文件批量打包（仅限于文件打包）
     *
     * @param sources
     * @param target
     * @return java.io.File
     * @author zxzhang
     * @date 2020/1/7
     */
    public static File pack(File target, File[] sources) {
        try (FileOutputStream out = new FileOutputStream(target); TarArchiveOutputStream os = new TarArchiveOutputStream(out)) {
            for (File file : sources) {
                os.putArchiveEntry(new TarArchiveEntry(file, file.getName()));
                IOUtils.copy(new FileInputStream(file), os);
                os.closeArchiveEntry();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return target;
    }

    /**
     * tar文件批量打包（支持文件&文件夹打包）
     *
     * @param destFilePath
     * @param files
     * @return java.lang.String
     * @author zxzhang
     * @date 2020/3/10
     */
    public static String tarFiles(String destFilePath, File... files) throws IOException {
        File destFile = new File(destFilePath);
        if (destFile.exists()) {
            LOG.error("********目标文件已存在，destFilePath：{}********" + destFilePath);
            return "目标文件已存在，destFilePath：" + destFilePath;
        }
        try (FileOutputStream fileOutputStream = new FileOutputStream(destFile);
                BufferedOutputStream bufferedWriter = new BufferedOutputStream(fileOutputStream);
                TarArchiveOutputStream tar = new TarArchiveOutputStream(bufferedWriter)) {

            tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

            for (File file : files) {
                addTarArchiveEntryToTarArchiveOutputStream(file, tar, "");
            }
        }
        return null;
    }

    /**
     * 添加文件到tar输出流中
     *
     * @param file
     * @param tar
     * @param prefix
     * @return void
     * @author zxzhang
     * @date 2020/3/10
     */
    private static void addTarArchiveEntryToTarArchiveOutputStream(File file, TarArchiveOutputStream tar, String prefix) throws IOException {
        TarArchiveEntry entry = new TarArchiveEntry(file, prefix + File.separator + file.getName());

        if (file.isFile()) {
            entry.setSize(file.length());
            tar.putArchiveEntry(entry);
            try (FileInputStream fileInputStream = new FileInputStream(file); BufferedInputStream input = new BufferedInputStream(fileInputStream);) {
                IOUtils.copy(input, tar);
            }
            tar.closeArchiveEntry();
        } else {
            tar.putArchiveEntry(entry);
            tar.closeArchiveEntry();
            prefix += File.separator + file.getName();
            File[] files = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    addTarArchiveEntryToTarArchiveOutputStream(f, tar, prefix);
                }
            }
        }
    }
    /**
     * tar文件压缩
     *
     * @param source
     * @return java.io.File
     * @author zxzhang
     * @date 2020/1/7
     */
    public static File compress(String outDir, File source) {
        File target = new File(outDir + File.separator + source.getName() + ".gz");
        FileInputStream in = null;
        GZIPOutputStream out = null;
        try {
            in = new FileInputStream(source);
            out = new GZIPOutputStream(new FileOutputStream(target));
            byte[] array = new byte[1024];
            int number = -1;
            while ((number = in.read(array, 0, array.length)) != -1) {
                out.write(array, 0, number);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }

            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }
        return target;
    }

    public static void main(String[] args) throws IOException {


        String pathname = "C:\\Users\\Administrator.DESKTOP-4PCK80Q\\Desktop\\test\\2\\t";
        File file = new File(pathname);
        
        File[] sources = file.listFiles();
        File target = new File("C:\\Users\\Administrator.DESKTOP-4PCK80Q\\Desktop\\test\\tar\\release_package.tar");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        pack(target, sources);
        stopWatch.stop();
        System.out.println("耗时:"+stopWatch.getLastTaskTimeMillis()/1000+"s");
        // compress(target);
        // String filePath = "/usr/local/oas";
        // String destFilePath = filePath + File.separator + "zhouhong" + ".tar";
        // tarFiles(destFilePath,
        // new File("/usr/local/oas/dockerFile/"),
        // new File("/usr/local/oas/笔记本文件/"),
        // new File("/usr/local/oas/UUID.info"));
        // compress("/usr/local/oas",new File(destFilePath));
    }
}